package com.baosight.sczx.zm.ct.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.ct.DataInterface;
import com.baosight.sczx.zm.ct.domain.ZMCTSmsModel;

/**
 * 
 * <p>Title: ServiceZMCT20.java</p>
 * <p>Description: 短信模板配置主表类</p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author wangkun
 * @version 1.0
 * <pre>Histroy:
 *          2012-6-14 下午04:23:53  wangkun  Create
 *</pre>
 */
public class ServiceZMCT20 extends ServiceEPBase 
{
	private static final String _REVERSE_MESSAGE = "定时消息";
	private static final String _TIMELY_MESSAGE = "即时消息";

	public EiInfo initLoad(EiInfo inInfo)
	{
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		return this.query(inInfo);
	}
	
	/**
	 * 
	 * <p>Function: query</p>
	 * <p>Description: 查询</p>
	 * <p>return value: ServiceZMCT20</p>
	 * <p>History:
	 *    2012-6-28下午02:18:27 wangkun
	 * </p>
	 *
	 */
	public EiInfo query(EiInfo inInfo)
	{
		EiInfo outInfo = super.query(inInfo, "ZMCTSmsModel.query", new ZMCTSmsModel());
		outInfo.addBlock(getMessageType());
		outInfo.addBlock(queryDataBaseSource());
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: insert</p>
	 * <p>Description: 新增</p>
	 * <p>return value: ServiceZMCT20</p>
	 * <p>History:
	 *    2012-6-28下午02:18:42 wangkun
	 * </p>
	 *
	 */
	public EiInfo insert(EiInfo inInfo) 
	{
		inInfo.getBlock("result").setCell(0, "fdKeyId", TablePk.getInstance().getNextValue("T_CT_SMS_MODEL"));//主键
		inInfo.getBlock("result").setCell(0, "fdStatus", "停用");//主键
		EiInfo outInfo = super.insert(inInfo, "ZMCTSmsModel.insert");		
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: update</p>
	 * <p>Description: 修改</p>
	 * <p>return value: ServiceZMCT20</p>
	 * <p>History:
	 *    2012-6-28下午02:19:06 wangkun
	 * </p>
	 *
	 */
	public EiInfo update(EiInfo inInfo) 
	{
		EiInfo outInfo = super.update(inInfo, "ZMCTSmsModel.update");
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: delete</p>
	 * <p>Description: 删除</p>
	 * <p>return value: ServiceZMCT20</p>
	 * <p>History:
	 *    2012-6-28下午02:19:15 wangkun
	 * </p>
	 *
	 */
	public EiInfo delete(EiInfo inInfo) 
	{
		EiInfo _temp = super.delete(inInfo, "ZMCTSmsModelSendtime.deleteWithModelId");
		if(_temp.getStatus() != -1)
		{
			_temp = super.delete(inInfo, "ZMCTSmsModelCreatetime.deleteWithModelId");
			if(_temp.getStatus() != -1)
			{
				_temp = super.delete(inInfo, "ZMCTSmsModelPerson.deleteWithModelId");
				if(_temp.getStatus() != -1)
				{
					_temp = super.delete(inInfo, "ZMCTSmsModel.delete");
				}
			}
		}
		
		EiInfo outInfo = this.query(inInfo);
		outInfo.setMsg(_temp.getMsg());
		outInfo.setStatus(_temp.getStatus());
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: use</p>
	 * <p>Description: 启用</p>
	 * <p>return value:EiInfo</p>
	 * <p>History:
	 *    2012-6-28下午02:19:26 wangkun
	 * </p>
	 *
	 */
	public EiInfo use(EiInfo inInfo)
	{
		EiInfo _temp = super.update(inInfo, "ZMCTSmsModel.updateUseStatus");
		EiInfo outInfo = this.query(inInfo);
		outInfo.setMsg(_temp.getMsg());
		outInfo.setDetailMsg(_temp.getDetailMsg());
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: unUse</p>
	 * <p>Description: 停用</p>
	 * <p>return value:EiInfo</p>
	 * <p>History:
	 *    2012-6-28下午02:19:37 wangkun
	 * </p>
	 *
	 */
	public EiInfo unUse(EiInfo inInfo)
	{
		EiInfo _temp = super.update(inInfo, "ZMCTSmsModel.updateUnuseStatus");
		EiInfo outInfo = this.query(inInfo);
		outInfo.setMsg(_temp.getMsg());
		outInfo.setDetailMsg(_temp.getDetailMsg());
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: validateSql</p>
	 * <p>Description: 验证sql语句</p>
	 * <p>return value:EiInfo</p>
	 * <p>History:
	 *    2012-6-28下午02:19:48 wangkun
	 * </p>
	 *
	 */
	public EiInfo validateSql(EiInfo inInfo)
	{
		String fdDsId = inInfo.get("fdDsId").toString();
		String fdSql = inInfo.get("fdSql").toString();
		
		if(fdSql.toLowerCase().contains(":currentdate"))
		{
			fdSql = fdSql.toLowerCase().replaceAll(":currentdate", StaticTools.getDate());
		}
		
		String fdSmsType = inInfo.get("fdSmsType").toString();
		DataInterface dataInterface = new DataInterface(fdDsId);
		if(!dataInterface.drive())
		{
			inInfo.setStatus(-1);
			inInfo.setMsg("找不到驱动程序类 ，加载驱动失败");
		}
		else if(!dataInterface.connect())
		{
			inInfo.setStatus(-1);
			inInfo.setMsg("数据库连接失败");
		}
		else
		{
			ResultSet rs = dataInterface.search(fdSql);
			if(rs == null)
			{
				inInfo.setStatus(-1);
				inInfo.setMsg("请检查sql语句的正确性，确保在选中的数据库配置中，可正常运行");
			}
			else if(fdSmsType.equals(_TIMELY_MESSAGE))
			{
				List _list = new ArrayList();
				try
				{
					while(rs.next())
					{
						String keyid = "";
						if(rs.getString("keyid") != null)
						{
							keyid = rs.getString("keyid");
						}
						
						if(_list.contains(keyid))
						{
							inInfo.setStatus(-1);
							inInfo.setMsg("sql语句的查询结果中，keyid字段的结果不唯一！");
							break;
						}
						
						_list.add(keyid);
					}
				}
				catch(SQLException ex)
				{
					inInfo.setStatus(-1);
					inInfo.setMsg("请检查sql语句的正确性，确保在选中的数据库配置中，可正常运行");
				}
			}
			else if(fdSmsType.equals(_REVERSE_MESSAGE))
			{
				try
				{
					int i=0; 
					while(rs.next())
					{
						i++;
						if(i >= 2)
						{
							inInfo.setStatus(-1);
							inInfo.setMsg("定时消息SQL的查询结果，必须为一条！");
							break;
						}
					}
				}
				catch(SQLException ex)
				{
					inInfo.setStatus(-1);
					inInfo.setMsg("请检查sql语句的正确性，确保在选中的数据库配置中，可正常运行");
				}
			}
		}
		
		dataInterface.colseDs();
		return inInfo;
	}
	
	public EiInfo decomposeColumns(EiInfo inInfo)
	{
		List _list = new ArrayList();
		EiBlock block = new EiBlock(EiConstant.resultBlock);
		EiColumn eiColumn = new EiColumn("fdFieldTname");
		eiColumn.setDescName("别名");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		eiColumn = new EiColumn("fdFieldName");
		eiColumn.setDescName("字段名");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		eiColumn = new EiColumn("TnameValue");
		eiColumn.setDescName("别名返回值");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		String fdSql = inInfo.get("fdSql").toString();
		String fdSmsType = inInfo.get("fdSmsType").toString();
		String fdColumns = fdSql.substring(0, fdSql.toLowerCase().indexOf("from"));
		fdColumns = fdColumns.substring(fdColumns.indexOf(" ")+1, fdColumns.trim().length());
		String[] columns = fdColumns.split(",");
		
		for(int i=0; i<columns.length; i++)
		{
			String column = columns[i];
			column = column.replaceAll("\t", " ");
			column = column.replaceAll("\r", " ");
			column = column.replaceAll("\n", " ");
			String fdFieldName = "";
			String fdFieldTname = "";
			if(column.toLowerCase().contains(" as "))
			{
				fdFieldName = column.trim().substring(0, column.trim().toLowerCase().indexOf("as")-1).trim();
				fdFieldTname = column.trim().substring(column.trim().lastIndexOf(" "), column.trim().length()).trim().replaceAll("\"", "");
			}
			else if(column.trim().contains(" "))
			{
				fdFieldName = column.trim().substring(0, column.trim().toLowerCase().indexOf(" ")).trim();
				fdFieldTname = column.trim().substring(column.trim().lastIndexOf(" "), column.trim().length()).trim().replaceAll("\"", "");
			}
			else
			{
				fdFieldName = fdFieldTname = column.trim();
			}
			
			if(fdSmsType.equals(_TIMELY_MESSAGE) && fdFieldTname.equals("mobileNum"))
			{
				continue;
			}
			Map inMap = new HashMap();
			inMap.put("fdFieldName", fdFieldName);
			inMap.put("fdFieldTname", fdFieldTname);
			inMap.put("TnameValue", "$"+fdFieldTname.toLowerCase()+"$");
			_list.add(inMap);
		}

		block.addRows(_list);
		inInfo.addBlock(block);
		return inInfo;
	}
	
	/**
	 * 
	 * <p>Function: queryDataBaseSource</p>
	 * <p>Description: 构造数据库数据源</p>
	 * <p>return value:EiBlock</p>
	 * <p>History:
	 *    2012-6-28下午02:20:03 wangkun
	 * </p>
	 *
	 */
	private EiBlock queryDataBaseSource()
	{
		EiBlock block = new EiBlock("cmes.ct.databasesource");
		
	    EiColumn eiColumn = new EiColumn("fdName");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		eiColumn = new EiColumn("fdKeyId");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		List _list = new ArrayList();
		_list = dao.query("ZMCTDataInterface.queryInterface", null);
		
		block.setRows(_list);
		return block;
	}
	
	/**
	 * 
	 * <p>Function: getMessageType</p>
	 * <p>Description: 构造消息类型</p>
	 * <p>return value:EiBlock</p>
	 * <p>History:
	 *    2012-6-28下午02:20:23 wangkun
	 * </p>
	 *
	 */
	private EiBlock getMessageType()
	{
	    EiBlock block = new EiBlock("cmes.ct.messageType");
			
	    EiColumn eiColumn = new EiColumn("value");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		Map inMap = new HashMap();
		inMap.put("value", _TIMELY_MESSAGE);
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", _REVERSE_MESSAGE);
		block.addRow(inMap);
		
		return block;	
	}
}
